{% extends 'web/template.html' %}

{% block title %}我的收藏{% endblock %}

{% block head %}
<!-- 预加载字体文件 -->
<link rel="preload" href="/static/layui/font/iconfont.woff2?v=282" as="font" type="font/woff2" crossorigin>

<style>
    /* 使用系统默认字体作为备选方案 */
    @font-face {
        font-family: 'layui-icon';
        src: url('/static/layui/font/iconfont.woff2?v=282') format('woff2'),
            url('/static/layui/font/iconfont.woff?v=282') format('woff'),
            url('/static/layui/font/iconfont.ttf?v=282') format('truetype');
        font-display: swap;
        /* 使用 swap 策略加快显示速度 */
    }

    /* 加载动画使用系统图标代替 Layui 图标 */
    .loading-spinner {
        display: inline-block;
        width: 30px;
        height: 30px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #1E9FFF;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    /* 修改内容网格布局，使用响应式设计 */
    .content-grid {
        display: grid;
        gap: 15px;
        /* 默认移动端布局：两列 */
        grid-template-columns: repeat(2, 1fr);
    }

    /* 平板设备：3列 */
    @media screen and (min-width: 768px) {
        .content-grid {
            grid-template-columns: repeat(3, 1fr);
        }
    }

    /* 桌面设备：4列 */
    @media screen and (min-width: 1024px) {
        .content-grid {
            grid-template-columns: repeat(4, 1fr);
        }
    }

    /* 大屏设备：5列 */
    @media screen and (min-width: 1440px) {
        .content-grid {
            grid-template-columns: repeat(5, 1fr);
        }
    }

    /* 优化卡片样式 */
    .content-card {
        background: #fff;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        transition: all 0.3s;
        /* 添加最小宽度确保内容不会过于拥挤 */
        min-width: 140px;
        position: relative;
        cursor: pointer;
    }

    .content-image {
        width: 100%;
        /* 根据屏幕宽度调整图片高度 */
        aspect-ratio: 3/4;
        object-fit: cover;
    }

    .content-info {
        padding: 10px;
    }

    .content-title {
        font-size: 13px;
        line-height: 1.4;
        color: #333;
        /* 限制标题最多显示2行 */
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;

        /* 移动端优化：调整字体大小 */
        @media screen and (max-width: 767px) {
            font-size: 12px;
        }
    }

    /* 修改分类样式 */
    .category-list {
        display: flex;
        gap: 8px;
        margin-bottom: 15px;
        flex-wrap: wrap;
        padding: 0 5px;
    }

    .category-item {
        padding: 6px 12px;
        border-radius: 4px;
        cursor: pointer;
        background: #f0f0f0;
        transition: all 0.3s;
        font-size: 13px;
        white-space: nowrap;
        position: relative;
        overflow: hidden;
    }

    /* 添加高亮样式 */
    .category-item.active {
        background: #1E9FFF;
        color: #fff;
        font-weight: 500;
    }

    /* 添加点击涟漪效果 */
    .category-item:active::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        transform: translate(-50%, -50%) scale(0);
        animation: ripple 0.6s linear;
    }

    @keyframes ripple {
        to {
            transform: translate(-50%, -50%) scale(2);
            opacity: 0;
        }
    }

    /* 悬停效果 */
    .category-item:hover {
        background: #e0e0e0;
    }

    .category-item.active:hover {
        background: #1890ff;
    }

    /* 容器边距响应式调整 */
    .container {
        padding: 15px;
        max-width: 1400px;
        margin: 0 auto;
    }

    @media screen and (max-width: 767px) {
        .container {
            padding: 10px;
        }
    }

    /* 优化分页在移动端的显示 */
    .pagination {
        margin-top: 20px;
        text-align: center;
    }

    @media screen and (max-width: 767px) {

        .layui-laypage a,
        .layui-laypage span {
            padding: 0 10px;
            margin: 0 2px;
        }
    }

    /* 修改删除按钮样式 */
    .delete-btn {
        position: absolute;
        top: 10px;
        right: 10px;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        opacity: 0;
        /* 默认隐藏 */
        transition: all 0.3s;
        z-index: 10;
    }

    /* PC端悬浮显示 */
    @media (hover: hover) {
        .content-card:hover .delete-btn {
            opacity: 1;
        }
    }

    /* 移动端始终显示 */
    @media (hover: none) {
        .delete-btn {
            opacity: 1;
            width: 28px;
            /* 移动端稍微小一点 */
            height: 28px;
            background: rgba(0, 0, 0, 0.6);
            /* 移动端背景色深一点 */
        }

        .delete-btn i {
            font-size: 14px;
        }

        /* 点击态效果 */
        .delete-btn:active {
            background: rgba(255, 71, 87, 0.8);
            transform: scale(0.95);
        }
    }

    /* 通用删除按钮样式 */
    .delete-btn i {
        color: #fff;
    }

    .delete-btn:hover {
        background: rgba(255, 71, 87, 0.8);
        transform: scale(1.1);
    }

    /* 优化移动端点击区域 */
    @media (max-width: 767px) {
        .delete-btn {
            top: 8px;
            right: 8px;
            padding: 8px;
            /* 增大点击区域 */
            margin: -8px;
            /* 补偿padding造成的位移 */
        }
    }

    /* 添加空状态样式 */
    .empty-state {
        text-align: center;
        padding: 40px 20px;
        color: #999;
    }

    .empty-state i {
        font-size: 48px;
        margin-bottom: 10px;
        display: block;
    }

    .empty-state .empty-text {
        font-size: 14px;
    }

    /* 插件按钮样式 */
    .plugin-button {
        position: fixed;
        right: 20px;
        bottom: 80px;
        width: 50px;
        height: 50px;
        background: #1E9FFF;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        cursor: pointer;
        z-index: 999;
        transition: all 0.3s;
    }

    .plugin-button:hover {
        transform: scale(1.1);
        background: #0d8aee;
    }

    .plugin-button i {
        font-size: 24px;
    }

    /* 移动端适配 */
    @media screen and (max-width: 767px) {
        .plugin-button {
            right: 15px;
            bottom: 70px;
            width: 45px;
            height: 45px;
        }
    }

    .content-time {
        font-size: 12px;
        color: #999;
        margin-top: 5px;
    }

    /* 优化插件菜单样式 */
    .plugin-menu {
        padding: 15px !important;
    }

    .plugin-menu-item {
        position: relative;
        margin-bottom: 10px;
        padding: 12px 15px;
        background: #f5f5f5;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s;
        color: #333;
        font-size: 14px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .plugin-menu-item:last-child {
        margin-bottom: 0;
    }

    .plugin-menu-item:hover {
        background: #e8e8e8;
    }

    .plugin-menu-item.active {
        background: #1E9FFF;
        color: #fff;
    }

    /* 添加状态标记 */
    .status-tag {
        font-size: 12px;
        padding: 2px 8px;
        border-radius: 4px;
        background: rgba(0, 0, 0, 0.1);
    }

    /* 添加已完成状态的样式 */
    .status-tag.completed {
        background: rgba(82, 196, 26, 0.15);
        color: #52c41a;
    }

    /* 添加开发中状态的样式 */
    .status-tag.developing {
        background: rgba(250, 173, 20, 0.15);
        color: #faad14;
    }

    /* 插件菜单滚动条样式 */
    .plugin-menu-scroll {
        max-height: 70vh;
        overflow-y: auto;
        overflow-x: hidden;
    }

    .plugin-menu-scroll::-webkit-scrollbar {
        width: 4px;
    }

    .plugin-menu-scroll::-webkit-scrollbar-thumb {
        background: #ddd;
        border-radius: 2px;
    }

    .plugin-menu-scroll::-webkit-scrollbar-track {
        background: #f5f5f5;
    }

    /* 移动端适配 */
    @media screen and (max-width: 767px) {
        .plugin-menu-item {
            padding: 10px 12px;
            font-size: 13px;
        }
    }
</style>
{% endblock %}

{% block content %}
{% include 'web/components/线路选择.html' %}

<div class="container">
    <!-- 返回上一页 -->
    {% include 'web/components/公共配置/返回上一页.html' %}
    <!-- 内容列表 -->
    <div class="content-grid" id="contentList"></div>

    <!-- 加载动画 -->
    <div class="loading" id="loading" style="display: none;">
        <div class="loading-spinner"></div>
    </div>
</div>

<!-- 插件按钮 -->
<div class="plugin-button" onclick="showPluginMenu()">
    <i class="layui-icon layui-icon-app"></i>
</div>

{% endblock %}

{% block script %}
{% include 'web/line2/解密模块.html' %}
{% include 'web/components/我的/我的收藏配置/制作收藏集.html' %}
{% include 'web/components/我的/我的收藏配置/查看收藏集.html' %}
<script>
    let currentCategory = null;
    let currentPage = 1;
    let currentKeyword = '';
    const contentList = document.getElementById('contentList');

    // 添加排序状态变量
    let isReversed = false;

    // 初始化
    window.onload = function () {
        loadLocalData();
    };

    function loadLocalData() {
        const LocalData = localStorage.getItem(localStorageKey);
        if (LocalData) {
            let data = JSON.parse(LocalData);
            if (data.length === 0) {
                showEmptyState();
                return;
            }

            // 根据时间戳排序
            data.sort((a, b) => {
                const timeA = new Date(a.timestamp).getTime();
                const timeB = new Date(b.timestamp).getTime();
                return isReversed ? timeB - timeA : timeA - timeB;
            });


            let dict = {}
            data.forEach((item, i) => {
                // 获取当前线路
                let line = item.line;
                // 判断dict中是否存在该线路
                if (!dict[line]) {
                    dict[line] = [];
                }
                dict[line].push(item);
            });
            renderContent(dict, Object.keys(dict));
        } else {
            showEmptyState();
        }
    }

    // 显示空状态
    function showEmptyState() {
        contentList.innerHTML = `
            <div class="empty-state">
                <i class="layui-icon layui-icon-face-cry"></i>
                <div class="empty-text">暂无收藏内容</div>
            </div>
        `;
    }

    // 修改渲染内容函数
    function renderContent(data, length) {
        length.forEach((line) => {
            contentList.innerHTML += data[line].map((item, index) => {
                return `
            <div class="content-card">
                <div class="delete-btn" onclick="deleteItem(event, '${item.url}')">
                    <i class="layui-icon layui-icon-close"></i>
                </div>
                <div onclick="viewDetail('${item.url}', '${line}')">
                    <img class="content-image" 
                         id="${line}-${index}"
                         alt="${item.title}"
                         src="${item.cover}"
                         data-line="${line}"
                         style="opacity: 0; transition: opacity 0.3s;">
                    <div class="content-info">
                        <div class="content-title">${item.title}</div>
                        <div class="content-time">${formatTime(item.timestamp)}</div>
                    </div>
                </div>
            </div>
            `
            }).join('');
        });

        length.forEach((line) => {
            for (let i = 0; i < data[line].length; i++) {
                let imgElement = document.getElementById(line + "-" + i);

                if (line == "line2") {
                    loadBackgroundImage(data[line][i].cover, imgElement);
                    imgElement.style.opacity = '1';
                } else {
                    imgElement.style.opacity = '1';
                }
            }

        });
    }

    // 删除收藏项
    function deleteItem(event, url) {
        event.stopPropagation(); // 阻止事件冒泡

        layer.confirm('确定要删除这条收藏吗？', {
            btn: ['确定', '取消'],
            title: '删除确认'
        }, function (index) {
            // 获取现有记录
            let records = JSON.parse(localStorage.getItem(localStorageKey) || '[]');

            // 过滤掉要删除的项
            records = records.filter(record => record.url !== url);

            // 保存更新后的数据
            localStorage.setItem(localStorageKey, JSON.stringify(records));

            // 重新加载数据
            contentList.innerHTML = '';
            if (records.length === 0) {
                showEmptyState();
            } else {
                loadLocalData();
            }

            layer.msg('删除成功', {
                icon: 1,
                time: 1500
            });

            layer.close(index);
        });
    }

    // 查看详情
    function viewDetail(url, line) {


        window.location.href = `/web/${line}/detail/?article_url=${encodeURIComponent(url)}`;


    }

    // 显示加载
    function showLoading() {
        document.getElementById('loading').style.display = 'block';
    }

    // 读取 localStorage 中的 videoRecords 数据
    async function getVideoRecords() {
        // 加载中
        layer.load(1);
        // 获取总线路
        let totalLine = document.querySelectorAll('.line-item');
        let new_videoRecords_copy = []

        let videoRecords = localStorage.getItem(localStorageKey);
        if (videoRecords) {
            let new_videoRecords = JSON.parse(videoRecords);
            for (let i = 0; i < totalLine.length; i++) {
                let line = totalLine[i];
                let lineNumber = line.getAttribute('data-line_url').split('/')[2];
                // 提取出 new_videoRecords 中 lineNumber 对应的 item
                let item = new_videoRecords.filter(item => item.line === lineNumber);
                // 对该线路发起请求(同步)
                let response = await axios({
                    url: ApiDomain + `api/scraper/hei_liao/${lineNumber}/get_category/`,
                    method: 'get',
                });
                let data = response.data.data;
                if (data.length > 0) {
                    for (let i = 0; i < item.length; i++) {
                        let new_domain = data[0].category_url.split('/')[2];
                        item[i].url = item[i].url.replace(item[i].url.split('/')[2], new_domain);
                        // 同步请求
                        let update_detail = await axios({
                            url: ApiDomain + `api/scraper/hei_liao/${lineNumber}/get_article_detail/`,
                            method: 'get',
                            params: {
                                article_url: item[i].url
                            }
                        });
                        let detail = update_detail.data.data.detail_imgs[0]
                        item[i].cover = detail
                        new_videoRecords_copy.push(item[i]);
                    }
                }

            }
        }
        console.log(new_videoRecords_copy);
        localStorage.setItem(localStorageKey, JSON.stringify(new_videoRecords_copy));
        // 加载完成
        layer.closeAll('loading');
        return [];
    }


    // 隐藏加载
    function hideLoading() {
        document.getElementById('loading').style.display = 'none';
    }

    // 显示插件菜单
    function showPluginMenu() {
        layer.open({
            type: 1,
            title: '功能列表',
            area: ['280px', 'auto'],
            maxHeight: '80vh',
            shade: 0.3,
            shadeClose: true,
            skin: 'plugin-menu',
            content: `
                <div class="plugin-menu-scroll">
                    <div class="plugin-menu-item" onclick="updateCollectionConfig()">
                        <span>更新收藏配置</span>
                        <span class="status-tag completed">已完成</span>
                    </div>
                    <div class="plugin-menu-item" onclick="toggleSort()">
                        <span>时间排序</span>
                        <span class="status-tag">${isReversed ? '最新在前' : '最早在前'}</span>
                    </div>
                    <div class="plugin-menu-item" onclick="make_collection()">
                        <span>制作收藏</span>
                        <span class="status-tag completed">已完成</span>
                    </div>
                    <div class="plugin-menu-item" onclick="viewCollection()">
                        <span>查看收藏集</span>
                        <span class="status-tag completed">已完成</span>
                    </div>
                </div>
            `
        });
    }

    // 更新收藏配置
    function updateCollectionConfig() {
        let str_text = `
            <div style="margin-bottom: 15px;">确定要更新收藏配置吗？此操作需要一点时间。</div>
            <div style="background: #f5f5f5; padding: 12px; border-radius: 6px; line-height: 1.6;">
                <div style="font-weight: bold; margin-bottom: 8px; color: #333;">为什么需要更新?</div>
                <div style="color: #666; font-size: 13px;">
                    • 本站的内容来自其他网站<br/>
                    • 当其他网站的地址变化时，图片和链接可能失效<br/>
                    • 建议每2天更新一次<br/>
                    • 发现图片无法显示时也请更新
                </div>
            </div>
        `;
        layer.confirm(str_text, {
            btn: ['确定', '取消'],
            title: '更新确认'
        }, function (index) {
            // 删除全部弹窗
            layer.closeAll();
            getVideoRecords()
        });
    }

    // 切换排序方式
    function toggleSort() {
        isReversed = !isReversed;
        contentList.innerHTML = '';
        loadLocalData();

        // 更新菜单中的排序状态
        const menuItems = document.querySelectorAll('.plugin-menu-item');
        menuItems.forEach(item => {
            if (item.textContent.includes('时间排序')) {
                const statusTag = item.querySelector('.status-tag');
                if (statusTag) {
                    statusTag.textContent = isReversed ? '最新在前' : '最早在前';
                }
            }
        });

        layer.msg(`已切换为${isReversed ? '最新在前' : '最早在前'}`, {
            icon: 1,
            time: 1500
        });
    }

    // 添加时间格式化函数
    function formatTime(timestamp) {
        const date = new Date(timestamp);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    }
</script>
{% endblock %}